package org.ohuang

import java.io.File
import java.io.FileReader
import java.io.FileWriter
import java.lang.StringBuilder
import java.util.TreeSet

fun findSimpleAllPageList(rootPath: String): List<String> {
    var list = ArrayList<String>()
    var findAllPackage = findAllPackage(rootPath)
    findAllPackage.forEach {
        if (!isMatch(it, list) && it != "/" && it != "") {
            list.add(it)
        }
    }
    return list
}

fun pageList2Simple( findAllPackage:Iterable<String>):List<String>{
    var list = ArrayList<String>()
    findAllPackage.forEach {
        if (!isMatch(it, list) && it != "/" && it != "") {
            list.add(it)
        }
    }
    return list
}

fun isMatch(s: String, list: Iterable<String>): Boolean {
    list.forEach {
        if (s.startsWith(it)) {
            return true
        }
    }
    return false

}

/**
 * 获取所有包名
 */
fun findAllPackage(rootPath: String): Set<String> {

    var hashSet = TreeSet<String>()
    var file = File(rootPath)
    file.listFiles()?.forEach {

        if (it.isDirectory) {
            if (it.name.startsWith("smali")) {

                findPackage(it.absolutePath, "", hashSet)

            }
        }
    }
    return hashSet
}

/**
 *
 */
fun findPackage(rootPath: String, path: String, set: MutableSet<String>) {
    val thisPath = rootPath + path
    var file = File(thisPath)
    if (file.exists()) {
        if (file.isFile) {
            set.add(path)
        } else {
            file.listFiles()?.forEach {
                var key = path + "/" + it.name
                if (it.isFile) {
                    set.add(path)
                } else {
                    findPackage(rootPath, key, set)
                }

            }
        }
    }
}


/**
 * 改变R.smali的值
 */
fun changeRSmali(path: String, map: HashMap<String, String>) {

    var fileReader = FileReader(path)

    var sb = StringBuilder()


    var readLines = fileReader.readLines()
    readLines.forEach {
        if (it.startsWith(".field public static final")) {
            var s = StringBuilder().append(it).toString().replace(".field public static final", "")
            var split = s.split(":I =")
            if (split.size != 2) {
                sb.append(it)
                sb.append("\n")
                return@forEach
            }
            var name = split[0].replace(" ", "")
            if (map.containsKey(name)) {
                var id = map[name]
                if (id != null && id!!.isNotEmpty()) {
                    var sp = StringBuilder().append(it).toString().replace(split[1].replace(" ", ""), id)
                    sb.append(sp)
                } else {
                    sb.append(it)
                }
            } else {
                sb.append(it)
            }

        } else {
            sb.append(it)
        }
        sb.append("\n")
    }


    var fileWriter = FileWriter(path)
    // 把替换完成的字符串写入文件内
    fileWriter.write(sb.toString().toCharArray());
    // 关闭文件流，释放资源
    fileReader.close()
    fileWriter.close()

}

fun copySmaliAndUpdaterSmali(path: String, path1: String, public: String) {
    var copySmali = copySmaliClass(path, path1)
    updateRSmali(public, copySmali)
}

fun updateRSmali(public: String, smaliList: MutableList<String>) {
    var readPublic = readPublic(public)

    val data = ArrayList<String>()

    smaliList.forEach {
        searchFileInPath(it, "R.smali", data)
    }

    data.forEach { itS ->
        println("----开始修改" + itS + "-----")
        var file1 = File(itS)
        var parentFile = file1.parentFile
        parentFile.listFiles()?.forEach { itF ->
            if (itF.isFile) {
                if (itF.name.startsWith("R\$")) {
                    var name = StringBuilder().append(itF.name).toString()
                    var key = name.replace("R\$", "").replace(".smali", "")
                    var hashMap = readPublic[key]
                    if (hashMap != null) {
                        changeRSmali(itF.absolutePath, hashMap)
                    }
                }
            }
        }
    }
}


/**
 * 修改public.xml 后更新R.smali
 */
fun updateRSmali2(public: String, path: String) {
    var readPublic = readPublic(public)
    var file = File(path)
    val data = ArrayList<String>()

    if (file.isDirectory) {
        searchFileInPath(file.absolutePath, "R.smali", data)
    } else if ("R.smali" == file.name) {
        data.add(file.absolutePath)
    }

    data.forEach { itS ->
        println("----开始修改" + itS + "-----")
        var file1 = File(itS)
        var parentFile = file1.parentFile
        parentFile.listFiles()?.forEach { itF ->
            if (itF.isFile) {
                if (itF.name.startsWith("R\$")) {
                    var name = StringBuilder().append(itF.name).toString()
                    var key = name.replace("R\$", "").replace(".smali", "")
                    var hashMap = readPublic[key]
                    if (hashMap != null) {
                        changeRSmali(itF.absolutePath, hashMap)
                    }
                }
            }
        }
    }
}

/**
 * 复制smali
 */
fun copySmaliClass(path: String, path1: String): MutableList<String> {
    var file = File(path)
    var file1 = File(path1)
    var index = 1
    file1.listFiles()?.forEach {
        if (it.isDirectory) {
            if (it.name.startsWith("smali_classes")) {
                var string = StringBuffer().append(it.name).toString().replace("smali_classes", "")
                var i = string.toInt()
                if (i > index) {
                    index = i
                }
            }
        }
    }
    var data = ArrayList<String>()
    val smaliPath = "$path1\\smali_classes"
    var smaliFile = File("$path\\smali")
    if (smaliFile.exists()) {
        index++
        println("------开始复制${smaliFile.name}到smali_classes" + index + "------")
        copyPathAllFile(smaliFile.absolutePath, smaliPath + index)
        data.add(smaliPath + index)
    }
    var p = 1
    while (true) {
        p++
        smaliFile = File("$path\\smali_classes$p")
        if (smaliFile.exists()) {
            index++
            println("------开始复制${smaliFile.name}到smali_classes" + index + "------")
            copyPathAllFile(smaliFile.absolutePath, smaliPath + index)
            data.add(smaliPath + index)
        } else {
            break
        }
    }
    return data
}

